<template>
	<view class="container">

		<!-- 页面头部 -->
		<view class="header">
			<view class="title">
				<text> 申請開店 </text>
			</view>
			<!-- <view class="sub-title">
				<text>未注册的手機號登入後將自動注册</text>
			</view> -->
		</view>
		<!-- 表单 -->
		<view class="login-form">
			<!-- 姓名 -->
			<view class="form-item">
				<input class="form-item--input" type="text" v-model="store_name" maxlength="11" placeholder="請輸入店鋪名字" />
			</view>
			<!-- 姓名 -->
			<view class="form-item">
				<input class="form-item--input" type="text" v-model="name" maxlength="11" placeholder="請輸入姓名" />
			</view>
			<!-- 手机号 -->
			<view class="form-item">
				<input class="form-item--input" type="text" v-model="mobile" placeholder="請輸入手機號碼" />
			</view>
			<!-- 身份证正面 -->
			<view class="form-item">
				<view class="image-list">
					<view class="image-preview" v-for="(image, imageIndex) in imageList" :key="imageIndex">
						<text class="image-delete iconfont icon-shanchu" @click="deleteImage(imageIndex)"></text>
						<image class="image" mode="aspectFill" :src="image.path"></image>
					</view>
					<view v-if="!imageList || imageList.length < maxImageLength" class="image-picker"
						@click="chooseImage()">
						<text class="choose-icon iconfont icon-camera"></text>
						<text class="choose-text">上傳身份證正面圖片</text>
					</view>
				</view>
			</view>
			<!-- 身份证反面 -->
			<view class="form-item">
				<view class="image-list">
					<view class="image-preview" v-for="(image, imageIndex) in imageList1" :key="imageIndex">
						<text class="image-delete iconfont icon-shanchu" @click="deleteImage(imageIndex, 1)"></text>
						<image class="image" mode="aspectFill" :src="image.path"></image>
					</view>
					<view v-if="!imageList1 || imageList1.length < maxImageLength" class="image-picker"
						@click="chooseImage(1)">
						<text class="choose-icon iconfont icon-camera"></text>
						<text class="choose-text">上傳身份證反面圖片</text>
					</view>
				</view>
			</view>
			<!-- 提交按钮 -->
			<view class="login-button" :class="{ disabled }" @click="handleform">
				<text>提交</text>
			</view>
		</view>


	</view>
</template>

<script>
	import * as UploadApi from '@/api/upload'
	import * as Verify from '@/utils/verify'
	import * as MerchantApi from '@/api/merchant'
	
	const maxImageLength = 1
	
	export default {
		components: {},

		props: {},

		data() {
			return {
				// 手机号
				mobile: '',
				maxImageLength,
				// 姓名
				name: '',
				store_name: '',
				imageList: [],
				imageList1: [],
				disabled: false,
				uploaded: []
			}
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		created() {},

		methods: {
			// 选择图片
			chooseImage(type) {
				const app = this
				const oldImageList = type ? app.imageList1 : app.imageList
				// 选择图片
				uni.chooseImage({
					count: maxImageLength - oldImageList.length,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success({
						tempFiles
					}) {
						// tempFiles = [{path:'xxx', size:100}]
						if (type) app.imageList1 = oldImageList.concat(tempFiles)
						else app.imageList = oldImageList.concat(tempFiles)
					}
				});
			},

			// 删除图片
			deleteImage(imageIndex, type) {
				if (type) this.imageList1.splice(imageIndex, 1)
				else this.imageList.splice(imageIndex, 1)

			},

			// 表单验证
			formValidation() {
				const app = this
				// 验证提交
				if (!app.validteMobile(app.mobile) || !app.validteImg(app.getImagesLength) || !app.validteName(app.name) || !app.validteStoreName(app.store_name)) {
					return false
				}
				return true
			},

			// 验证身份图片
			validteImg(len) {
				if (len < 2) {
					this.$toast('請先上傳身份證圖片')
					return false
				}
				return true
			},

			// 验证姓名
			validteName(str) {
				if (Verify.isEmpty(str)) {
					this.$toast('請先輸入姓名')
					return false
				}
				return true
			},
			
			// 验证店鋪名字
			validteStoreName(str) {
				if (Verify.isEmpty(str)) {
					this.$toast('請輸入店鋪名字')
					return false
				}
				return true
			},

			// 验证手机号
			validteMobile(str) {
				if (Verify.isEmpty(str)) {
					this.$toast('請先輸入手機號')
					return false
				}
				if (!Verify.isMobile(str)) {
					this.$toast('請輸入正確格式的手機號')
					return false
				}
				return true
			},


			// 点击提交
			handleform() {
				const app = this
				if (!app.isLoading && app.formValidation()) {
					app.handleSubmit()
				}
			},

			// 确认提交
			submitApply() {
				const app = this
				app.isLoading = true
				MerchantApi.storeApply({
						store_name: app.store_name,
						id_name: app.name,
						mobile: app.mobile,
						id_front: app.uploaded[0][0],
						id_back: app.uploaded[1][0]
					})
					.then(result => {
						// 显示提交成功
						app.$toast(result.message)
						// 跳转回原页面
						setTimeout(() => {
							uni.navigateBack(1)
						}, 2000)
					})
					.catch(err => {
						app.$toast(result.message)
					})
					.finally(() => app.isLoading = false)
			},

			// 统计图片数量
			getImagesLength() {
				const {
					imageList,
					imageList1
				} = this
				let imagesLength = imageList.length + imageList1.length
				return imagesLength
			},
			// 表单提交
			handleSubmit() {
				const app = this
				// 判断是否重复提交
				if (app.disabled === true) return false
				// 按钮禁用
				app.disabled = true
				// 判断是否需要上传图片
				const imagesLength = app.getImagesLength()
				if (imagesLength > 0) {
					app.uploadFile()
						.then(() => {
							console.log('then')
							app.submitApply()
						})
						.catch(err => {
							console.log('catch')
							app.disabled = false
							if (err.statusCode !== 0) {
								app.$toast(err.errMsg)
							}
							console.log('err', err)
						})
				} else {
					app.submitApply()
				}
			},
			// 上传图片
			uploadFile() {
				const app = this
				const {
					imageList,
					imageList1
				} = app
				// 整理上传文件路径
				let files = []
				const images = imageList.map(image => image)
				files.push({
					formDataIndex: 0,
					images
				})
				const images1 = imageList1.map(image => image)
				files.push({
					formDataIndex: 1,
					images: images1
				})
				// 批量上传
				return new Promise((resolve, reject) => {
					Promise.all(files.map((file, index) => {
							return new Promise((resolve, reject) => {
								UploadApi.image1(file.images)
									.then((result) => {
										app.uploaded[index] = result
										resolve(result)
									})
									.catch(reject)
							})
						}))
						.then(resolve, reject)
				})
			}
		}

	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 100rpx 60rpx;
		min-height: 100vh;
		background-color: #fff;
	}

	// 页面头部
	.header {
		margin-bottom: 60rpx;

		.title {
			color: #191919;
			font-size: 54rpx;
		}

		.sub-title {
			margin-top: 20rpx;
			color: #b3b3b3;
			font-size: 28rpx;
		}
	}

	// 输入框元素
	.form-item {
		display: flex;
		padding: 18rpx;
		border-bottom: 1rpx solid #f3f1f2;
		margin-bottom: 30rpx;
		min-height: 96rpx;

		&--input {
			font-size: 28rpx;
			letter-spacing: 1rpx;
			flex: 1;
			height: 100%;
		}

		&--parts {
			min-width: 100rpx;
			height: 100%;
		}

	}

	// 提交按钮
	.login-button {
		width: 100%;
		height: 86rpx;
		margin-top: 80rpx;
		background: linear-gradient(to right, #ecb53c, #ff9211);
		color: #fff;
		border-radius: 80rpx;
		box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.1);
		letter-spacing: 5rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>
